package com.dzm.content.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dzm.constants.RabbitConstant;
import com.dzm.constants.RedisConstant;
import com.dzm.content.entity.Content;
import com.dzm.content.service.ContentService;
import com.dzm.content.mapper.ContentMapper;
import com.dzm.content.vo.SearchVo;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author Dzm
* @description 针对表【tb_content】的数据库操作Service实现
* @createDate 2024-09-13 16:48:17
*/
@Service
public class ContentServiceImpl extends ServiceImpl<ContentMapper, Content>
    implements ContentService{

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public Page<Content> search(Integer pageNum, Integer pageSize, SearchVo vo) {
        LambdaQueryWrapper<Content> wrapper = new LambdaQueryWrapper<>();
        if(vo != null) {
            wrapper.eq(vo.getCateId() != null && vo.getCateId() != 0, Content::getCategoryId, vo.getCateId())
                    .like(StrUtil.isNotBlank(vo.getTitle()), Content::getTitle, vo.getTitle());
        }

        Page<Content> pageModel = this.page(new Page<>(pageNum, pageSize), wrapper);

        return pageModel;
    }

    @Override
    public List<Content> getBanners() {
        Collection<Object> collection = redisTemplate.opsForHash().entries(RedisConstant.BANNER_LIST).values();
        List<Content> list = null;

        if(!CollectionUtils.isEmpty(collection)) {
            list = collection.stream().map(m -> (Content) m).collect(Collectors.toList());
        }else {
            LambdaQueryWrapper<Content> wrapper = new LambdaQueryWrapper<Content>().eq(Content::getCategoryId, 2L);
            list = this.list(wrapper);

            //存入缓存
            for (Content content : list) {
//                redisTemplate.opsForHash().put(RedisConstant.BANNER_LIST, content.getId(), content);
                rabbitTemplate.convertAndSend(RabbitConstant.CONTENT_EXC, RabbitConstant.CONTENT_EXC_SAVE, content);
            }
        }

        return list;
    }
}




